package com.blog.cmrpersonalblog.task;

import com.blog.cmrpersonalblog.config.RankingConfig;
import com.blog.cmrpersonalblog.service.RankingService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 排行榜数据刷新定时任务
 * 每周定期刷新榜单数据
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "ranking.refresh.enabled", havingValue = "true", matchIfMissing = true)
public class RankingRefreshTask {

    @Resource
    private RankingService rankingService;

    @Resource
    private RankingConfig rankingConfig;

    /**
     * 每周定时刷新榜单
     * 默认每周一凌晨2点执行
     * cron表达式: 秒 分 时 日 月 周
     * 0 0 2 ? * MON 表示每周一凌晨2点
     */
    @Scheduled(cron = "${ranking.refresh.cron:0 0 2 ? * MON}")
    public void weeklyRefreshRankings() {
        log.info("========== 开始每周榜单刷新 ==========");
        log.info("刷新时间: {}", LocalDateTime.now());

        try {
            long startTime = System.currentTimeMillis();

            // 获取刷新前统计信息
            RankingService.RankingStatistics beforeStats = rankingService.getStatistics();
            log.info("刷新前统计 - 文章榜: {}条, 作者榜: {}条, 收藏榜: {}条, 总计: {}条",
                beforeStats.getArticleRankingCount(),
                beforeStats.getAuthorRankingCount(),
                beforeStats.getCollectionRankingCount(),
                beforeStats.getTotalRankingCount());

            // 执行榜单刷新
            rankingService.refreshAllRankings();

            // 获取刷新后统计信息
            RankingService.RankingStatistics afterStats = rankingService.getStatistics();
            long endTime = System.currentTimeMillis();

            log.info("刷新后统计 - 文章榜: {}条, 作者榜: {}条, 收藏榜: {}条, 总计: {}条",
                afterStats.getArticleRankingCount(),
                afterStats.getAuthorRankingCount(),
                afterStats.getCollectionRankingCount(),
                afterStats.getTotalRankingCount());

            log.info("榜单刷新完成，耗时: {}ms", endTime - startTime);
            log.info("下次刷新时间: {}", rankingService.getNextUpdateTime());
            log.info("========== 每周榜单刷新结束 ==========");

        } catch (Exception e) {
            log.error("每周榜单刷新失败", e);
        }
    }

    /**
     * 每小时检查并清理过期数据（可选）
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void hourlyMaintenance() {
        log.debug("执行榜单维护任务...");
        try {
            // 可以在这里添加一些维护逻辑，比如清理过期的历史数据等
            RankingService.RankingStatistics stats = rankingService.getStatistics();
            log.debug("当前榜单统计 - 总计: {}条", stats.getTotalRankingCount());
        } catch (Exception e) {
            log.error("榜单维护任务失败", e);
        }
    }
}
